<template>
  <el-dialog class="partyInfo"  v-model="formVisible" center draggable width="80%" @close="closeDialog" :fullscreen="isFullscreen">
    <template #header="{close, titleId, titleClass}" class="title">
      <span style="text-align: center">{{title}}</span>
      <span :style="scoreLabelStyle(partyScoreLabel)">（{{partyScoreLabel}}）<span style="color: #606266" v-if="partyCensorStatus === '已审核'">调整后: <span :style="scoreLabelStyle(rankCensorData.scoreLabel)">{{rankCensorData.scoreLabel}}</span></span> </span>
      <span :style="scoreCensorStatusStyle(partyCensorStatus)">&emsp;{{partyCensorStatus}}</span>
    </template>
    <svg-icon class="maximize" name="maximize" size="16" @click="isFullscreen = !isFullscreen"></svg-icon>
    <el-tabs v-model="activePartyType" @tab-click="handleClick" class="tabs" :class="isFullscreen ? 'full': ''">
      <el-tab-pane  v-for="(form, index) in partyForm" :label="form.partyType" :name="index">
        <el-scrollbar :height="isFullscreen ? '87vh':'67vh'">
          <el-table class="party" :data="form.property" border
                    :span-method="objectSpanMethod" :scrollbar-always-on="true"
                    :header-cell-style="{'text-align': 'center'}"
                    :cell-style="cellStyle"
                    empty-text="请添加党建信息" style="width: 100%;height: 100%; overflow-x: auto">
            <el-table-column type="index" label="序号" align="center" width="80"/>
            <el-table-column prop="projectName" label="项目" align="left" min-width="100" style="font-family:方正黑体_GBK 黑体 !important;"/>
            <el-table-column prop="checkey" label="检查要点" align="left" min-width="120" style="font-family:方正黑体_GBK 黑体">
              <template #default="scope" style="text-align: left">
                <div v-for="(val,key)  in scope.row.checkey">
                  {{key+1}}.{{val}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="evaluationType" label="类别" min-width="200" align="left">
              <template #default="scope">
                <div :style="strictlyTextColor(scope.row)">{{scope.row.evaluationType}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="evaluation" label="主要评价指标" min-width="180" align="left">
              <template #default="scope">
                <div :style="strictlyTextColor(scope.row)">{{scope.row.evaluation}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="appraise" label="评价" width="80" align="left">
              <template #default="scope" style="text-align: left">
                <el-checkbox v-model="scope.row.isCheck" :label="getAppraiseLabel(scope.row.evaluationType)" size="large" @change="handleUpdateScore(form)" :disabled="formOperate !== 'edit'"/>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="180" align="left">
              <template #default="scope" style="text-align: left">
                <el-input
                    :disabled="!scope.row.isCheck"
                    v-model="scope.row.remark"
                    maxlength="256"
                    placeholder="请输入备注信息"
                    show-word-limit
                    type="textarea"/>
              </template>
            </el-table-column>
          </el-table>
          <el-button v-show="formOperate === 'edit' " :loading="loading" type="primary" style="width:100%;margin-top:20px;"
                     @click.prevent="handleUpdate(form)">保 存</el-button>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="等次调整情形" name="等次调整情形" v-if="partyForm.length > 0">
        <el-scrollbar height="67vh">
          <el-table class="party" :data="rankData" border
                    :span-method="rankSpanMethod"
                    :header-cell-style="{'text-align': 'center'}"
                    empty-text="请添加等次配置" style="width: 100%;height: 100%">
            <el-table-column type="index" label="序号" align="center" width="80"/>
            <el-table-column prop="type" label="类别" align="center" min-width="100"/>
            <el-table-column prop="situation" label="情形" align="center" min-width="30"/>
            <el-table-column prop="exist" label="有/无" align="center" min-width="80">
              <template #default="scope" style="text-align: left">
                <el-checkbox v-model="scope.row.isCheck" label="有" size="large" @change="handleUpdateRankScore" :disabled="formOperate !== 'edit'"/>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="left" min-width="180">
              <template #default="scope" style="text-align: left">
                <el-input
                    :disabled="!scope.row.isCheck"
                    v-model="scope.row.remark"
                    maxlength="256"
                    placeholder="请输入备注信息"
                    show-word-limit
                    type="textarea"/>
              </template>
            </el-table-column>
          </el-table>
          <el-button v-show="formOperate === 'edit' " :loading="loading" type="primary" style="width:100%;margin-top:20px;"
                     @click.prevent="handleUpdateRank">保 存</el-button>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="等次调整审核" name="等次调整审核" v-if="partyForm.length > 0">
        <el-scrollbar height="67vh">
          <h2>一、客观评定结论:</h2>
          <h1 :style="scoreLabelStyle(partyScoreLabel)" style="left: 0; right: 0;text-align: center">{{partyScoreLabel}}</h1>
          <h2>二、等次调整情形</h2>
          <el-table class="party" :data="rankCheckedData" border
                    :span-method="rankCheckedSpanMethod"
                    :header-cell-style="{'text-align': 'center'}"
                    empty-text="请添加等次配置" style="width: 100%;height: 100%">
            <el-table-column type="index" label="序号" align="center" width="80"/>
            <el-table-column prop="type" label="类别" align="center" min-width="100"/>
            <el-table-column prop="situation" label="情形" align="center" min-width="30"/>
            <el-table-column prop="remark" label="备注" align="left" min-width="180">
              <template #default="scope" style="text-align: left">
                <el-input
                    :disabled="!scope.row.isCheck"
                    v-model="scope.row.remark"
                    maxlength="256"
                    placeholder="请输入备注信息"
                    show-word-limit
                    type="textarea"/>
              </template>
            </el-table-column>
          </el-table>
          <h2>三、调整后评定结论</h2>
          <el-form ref="refCensorForm" :model="rankCensorData" label-width="120px">
            <h1 :style="scoreLabelStyle(rankCensorData.scoreLabel)" style="left: 0; right: 0;text-align: center">{{rankCensorData.scoreLabel}}</h1>
            <el-form-item prop="scoreLabel" label="最終评定等次:">
              <el-select v-model="rankCensorData.scoreLabel" style="width: 100%" :disabled="!userInfo.approver || partyCensorStatus === '已审核'">
                <el-option
                    v-for="item in executeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item prop="remark" label="备注:">
              <el-input
                  v-model="rankCensorData.remark"
                  maxlength="256"
                  placeholder="请输入备注信息"
                  show-word-limit
                  :disabled="!userInfo.approver || partyCensorStatus === '已审核'"
                  type="textarea"/>
            </el-form-item>
            <div style="display: flex;justify-content: flex-start; flex-direction: row-reverse;gap: 20px" v-if="userInfo.approver && partyCensorStatus !== '已审核'  ">
              <el-button type="primary" v-on:click="handleCensor(rankCensorData)">提交审定</el-button>
              <el-button type="danger" v-on:click="handleResetAssess(rankCensorData)">重新评估</el-button>
            </div>
          </el-form>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "PartyInfo"
}
</script>

<script setup lang="ts">
import {IPartyForm, IParty, IProperty, IExecute, IRankAdjust, IRankCensor} from "@/iwb/IParty";
import {PropType, reactive, ref, watch} from "vue";
import {FormInstance, FormRules, TableColumnCtx, TabsPaneContext} from "element-plus";
import {getRankAdjust, updatePartyBuilding} from "@/api/party";
import {DialogUtils} from "@/utils/DialogUtils";
import {Utils} from "@/utils/utils";
import {FileUtils} from "@/utils/FileUtils";
import {useUserStore} from "@/store/user";
import {storeToRefs} from "pinia";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  operate: {
    type: String,
    default: 'edit',
  },
  data: Array as PropType<Array<IParty>>
});

const loading = ref(false);
const userStore = useUserStore();
const {userInfo} = storeToRefs(userStore);
const formVisible = ref(false);
const isFullscreen = ref(false);
const formOperate = ref('edit');
const title = ref('党建基本信息');
const partyInfo = ref([] as Array<IParty>);
const partyForm = ref([] as Array<IPartyForm>);
const activePartyType = ref(0);
const partyScoreLabel = ref('');
const partyCensorStatus = ref('');
const rankCensorData = ref({} as IRankCensor);

const executeOptions = [{
  value: '优秀',
  label: '优秀',
},{
  value: '良好',
  label: '良好',
},{
  value: '一般',
  label: '一般',
},{
  value: '不力',
  label: '不力',
}];
const closeDialog = () => {
  formVisible.value = false;
  formOperate.value = '';
  partyInfo.value = [];
  partyForm.value = [];
  activePartyType.value = 0;
  minRankUpdateId = undefined;
  emit('reload:data');
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
  //console.log(tab, event)
  if (tab.props.name === '等次调整情形') {
    (async () => {
      try {
        rankData.value = [];
        let res = await getRankAdjust(1, 1);
        const totalCount = res.data.total;
        res = await getRankAdjust(1, totalCount);
        let bonus = [] as Array<IExecute>;
        let negative = [] as Array<IExecute>;
        for (let i=0; i<partyForm.value.length; ++i) {
          const item = partyForm.value[i];
          if (item) {
            bonus = getBonusOrNegative(bonus, item.bonus);
            negative = getBonusOrNegative(negative, item.negative);
          }
        }
        rankData.value = res.data.ranks;
        rankData.value.forEach((rank: IRankAdjust) => {
          if (rank.type === '提升等次') {
            for (let i=0; i<bonus.length; ++i) {
              const item: any = bonus[i];
              if (item) {
                const jsonItem: IExecute = JSON.parse(item);
                if (jsonItem.data === rank.situation) {
                  rank.isCheck = true;
                  rank.remark = jsonItem.remark;
                  break;
                }
              }
            }
          } else if (rank.type === '降低等次') {
            for (let i=0; i<negative.length; ++i) {
              const item: any = negative[i];
              if (item) {
                const jsonItem: IExecute = JSON.parse(item);
                if (jsonItem.data === rank.situation) {
                  rank.isCheck = true;
                  rank.remark = jsonItem.remark;
                  break;
                }
              }
            }
          }
        })
      } catch (e) {
        console.error(e);
      }
    })();
  } else if (tab.props.name === '等次调整审核') {
    rankCheckedData.value = [];
    let bonus = [] as Array<IExecute>;
    let negative = [] as Array<IExecute>;
    for (let i=0; i<partyForm.value.length; ++i) {
      const item = partyForm.value[i];
      if (item) {
        bonus = getBonusOrNegative(bonus, item.bonus);
        negative = getBonusOrNegative(negative, item.negative);
      }
    }
    /**
     * 提升等次
     */
    for (let i=0; i<bonus.length; ++i) {
      const rank = {} as IRankCensor;
      const item: any = bonus[i];
      if (item) {
        const jsonItem: IExecute = JSON.parse(item);
        rank.situation = jsonItem.data ? jsonItem.data : '';
        rank.remark = jsonItem.remark;
        rank.type = '提升等次';
        rank.id = rankCheckedData.value.length;
        rankCheckedData.value.push(rank);
      }
    }
    /**
     * 降低等次
     */
    for (let i=0; i<negative.length; ++i) {
      const rank = {} as IRankCensor;
      const item: any = negative[i];
      if (item) {
        const jsonItem: IExecute = JSON.parse(item);
        rank.situation = jsonItem.data ? jsonItem.data : '';
        rank.remark = jsonItem.remark;
        rank.type = '降低等次';
        rank.id = rankCheckedData.value.length;
        rankCheckedData.value.push(rank);
      }
    }
  }
}

interface CellStyleMethodProps {
  row: IProperty
  column: TableColumnCtx<IProperty>
  rowIndex: number
  columnIndex: number
}
const scoreLabelStyle = (label: string) => {
  return label === '优秀' ? 'color: green' : label === '良好' ? 'color: #67C23A' : label === '一般' ? 'color: #E6A23C' :'color: red'
}
const scoreCensorStatusStyle = (status: string) => {
  return status === '已审核' ? 'color: green' : status === '待审核'  ? 'color: #E6A23C' : 'color: red'
}
const cellStyle = ({ row, column, rowIndex, columnIndex }: CellStyleMethodProps) => {
  if (columnIndex === 1 || columnIndex === 2) {
    return {
      fontFamily: '黑体 方正黑体_GBK',
      fontWeight: 700
    }
  } else {
    return {
      fontFamily: '方正仿宋_GBK'
    }
  }
}

const strictlyTextColor = (row: IProperty) => {
  return row.evaluationType === '有无严禁发生的行为' ? "color: #A71E32;font-weight: 700;" : '';
}

const changeEvaluationType = (partyType: string, row: IProperty) => {
  if (row.evaluationType === '有无严禁发生的行为') {
    return partyType === '坚持党对军队绝对领导方面' ?
        '(有坚持党对军队绝对领导方面严禁发生的问题)' : partyType === '领导推进备战打仗方面' ? '有领导推进备战打仗方面严禁发生的问题' :'(无坚持党对军队绝对领导、领导推进备战打仗方面严禁发生的问题；有其他方面的问题)';
  }
}
/**
 * 获取信息
 * @param execute
 * @param evaluation
 */
const getExecute = (execute: Array<any>, evaluation: string): IExecute | undefined => {
  if (execute) {
    for (let i=0; i<execute.length; ++i) {
      const item = execute[i];
      const jsonExecute: IExecute = JSON.parse(item);
      if (jsonExecute.data === evaluation) {
        return jsonExecute;
      }
    }
  }
  return undefined;
}

const getMinRankUpdateId = (id: number) => {
  if (minRankUpdateId === undefined) {
    return id;
  }
  return minRankUpdateId > id ? id : minRankUpdateId;
}

const getBonusOrNegative = (oldBonus: Array<IExecute>, bonus: Array<IExecute>): Array<IExecute> => {
  return bonus && bonus.length > 0 ? bonus : oldBonus;
}
/**
 * 设置党建编辑基本信息
 * @param partyInfo
 */
const initPartyInfo = (partyInfo: Array<IParty>) => {
  partyForm.value = [];
  activePartyType.value = 0;
  minRankUpdateId = undefined;
  if (partyInfo && partyInfo.length > 0) {
    partyScoreLabel.value = adjustScore(partyInfo[0].score);
    partyCensorStatus.value = partyInfo[0].censorStatus;
    rankCensorData.value.scoreLabel = adjustScore(partyInfo[0].censorScore);
    rankCensorData.value.remark = partyInfo[0].censorRemark;
    title.value = partyInfo[0].partyName + '的' + partyInfo[0].partyTime + '党组织落实全面从严治党主体责任评估';
    const partyTypeMap = new Map();
    partyInfo.forEach((item: IParty) => {
      partyTypeMap.set(item.partyType, item.partyType);
    })

    partyTypeMap.forEach((value, key) => {
      let formIndex = partyForm.value.length;
      const form = {} as IPartyForm;
      form.property = [];
      partyInfo.filter(item => item.partyType === key).forEach((item: IParty) => {
        form.partyName = item.partyName;
        form.partyTime = item.partyTime;
        form.partyType = item.partyType;
        form.bonus = getBonusOrNegative(form.bonus, item.bonus);
        form.negative = getBonusOrNegative(form.negative, item.negative);
        item.evaluation1?.forEach((evaluation: string, index: number) => {
          const property = {} as IProperty;
          minRankUpdateId = getMinRankUpdateId(item.id);
          property.id = item.id;
          property.index = formIndex;
          property.projectName = item.projectName;
          property.checkey = item.checkey
          property.evaluation = index + 1 + '.' + evaluation;
          const execute = getExecute(item.execute1, property.evaluation);
          if (execute) {
            property.isCheck = true;
            property.execute = execute.data;
            property.remark = execute.remark;
          }
          property.evaluationType = '工作推进与制度执行';
          form.property.push(property);
        })

        item.evaluation2?.forEach((evaluation: string, index: number) => {
          const property = {} as IProperty;
          minRankUpdateId = getMinRankUpdateId(item.id);
          property.id = item.id;
          property.index = formIndex;
          property.projectName = item.projectName;
          property.checkey = item.checkey
          property.evaluation = index + 1 + '.' + evaluation;
          const execute = getExecute(item.execute2, property.evaluation);
          if (execute) {
            property.isCheck = true;
            property.execute = execute.data;
            property.remark = execute.remark;
          }
          property.evaluationType = '工作质量与实际成效';
          form.property.push(property);
        })

        item.evaluation3?.forEach((evaluation: string, index: number) => {
          const property = {} as IProperty;
          minRankUpdateId = getMinRankUpdateId(item.id);
          property.id = item.id;
          property.index = formIndex;
          property.projectName = item.projectName;
          property.checkey = item.checkey
          property.evaluation = index + 1 + '.' + evaluation;
          const execute = getExecute(item.execute3, property.evaluation);
          if (execute) {
            property.isCheck = true;
            property.execute = execute.data;
            property.remark = execute.remark;
          }
          property.evaluationType = '有无严禁发生的行为';
          form.property.push(property);
        })
      })
      partyForm.value.push(form);
    })
  }
}

const adjustScore = (score: number): string => {
  return score > 90 ? '优秀': score > 80 ? '良好': score > 70 ? '一般' : '不力';
}

const adjustScoreLabel = (scoreLabel: string): number => {
  return scoreLabel === '优秀' ? 91 : scoreLabel === '良好' ? 81 : scoreLabel === '一般' ? 71 : 61;
}
/**
 * 根据数据计算得分
 * @param partForm
 */
const computeScore = (partForm: Array<IPartyForm>): IParty => {
  let party = {} as IParty;
  let isCheckNum: number = 0;
  let allCheckNum: number = 0;
  let allElementEvaluation1 = 0;  //工作推进与制度执行方面
  let allElementEvaluation2 = 0;  //工作质量与实际成效方面
  let allElementEvaluation3 = 0;  //严禁发生的行为方面
  let haveElementExecute1 = 0;    //工作推进与制度执行方面
  let haveElementExecute2 = 0;    //工作质量与实际成效方面
  let haveElementExecute3 = 0;    //严禁发生的行为方面
  let hasOneVoteNo = false;       //是否存在一票否决
  let hasBonus = false;
  let hasNegative = false;
  for (let i=0; i<partForm.length && !hasOneVoteNo; ++i) {
    const form = partForm[i];
    if (!form) continue;
    party.partyName = form.partyName;
    party.partyTime = form.partyTime;
    isCheckNum += form.property.filter(item => item.isCheck).length;
    allCheckNum += form.property.length;
    //判断是否有加减分项目
    if (form.bonus) {
      hasBonus = hasBonus || form.bonus.length > 0;
    }
    if (form.negative) {
      hasNegative = hasNegative || form.negative.length > 0;
    }
    for(let j=0; j<form.property.length; ++j) {
      const property = form.property[j];
      if (!property) continue;
      if (property.evaluationType === '工作推进与制度执行') {
        allElementEvaluation1 += 1;
        haveElementExecute1 += property.isCheck ? 1 : 0;
      } else if (property.evaluationType === '工作质量与实际成效') {
        allElementEvaluation2 += 1;
        haveElementExecute2 += property.isCheck ? 1 : 0;
      } else if (property.evaluationType === '有无严禁发生的行为') {
        //直接否决
        if (form.partyType === '坚持党对军队绝对领导方面' || form.partyType === '领导推进备战打仗方面') {
          hasOneVoteNo = hasOneVoteNo || property.isCheck;
        }
        allElementEvaluation3 += 1;
        haveElementExecute3 += property.isCheck ? 1 : 0;
      }
    }
  }
  /**
   * 计算等次
   */
  if (hasOneVoteNo) {
    //如果存在一票否决发生的问题
    party.score = 61;
    party.scoreLabel = adjustScore(party.score);
  } else {
    let score = 0;
    const executeScore1 = Math.floor(haveElementExecute1 * 100 / allElementEvaluation1);
    const executeScore2 = Math.floor(haveElementExecute2 * 100 / allElementEvaluation2);
    const executeScore3 = Math.floor(haveElementExecute3 * 100 / allElementEvaluation3);
    //console.warn(executeScore1)
    //console.warn(executeScore2)
    //console.warn(executeScore3)
    //优秀
    if (executeScore1 > 90 && executeScore2 > 90) {
      score = 91;
    } else if (executeScore1 > 80 && executeScore2 > 80) {
      //良好
      score = 81;
    } else if (executeScore1 > 70 && executeScore2 > 70) {
      //一般
      score = 71
    } else {
      //不力
      score = 61;
    }
    //判断是否有加减分项目
    console.warn(hasBonus);
    console.warn(hasNegative);
    score += hasBonus ? 10 : 0;
    score -= hasNegative ? 10 : 0;
    //设置总分
    party.score = score;
    partyScoreLabel.value = adjustScore(score);
    party.scoreLabel = adjustScore(party.score);
  }

  return party;
}

interface RankSpanMethodProps {
  row: IRankAdjust
  column: TableColumnCtx<IRankAdjust>
  rowIndex: number
  columnIndex: number
}

const rankData = ref([] as Array<IRankAdjust>)
const rankCheckedData = ref([] as Array<IRankCensor>)

const rankSpanMethod = ( {
                           row,
                           column,
                           rowIndex,
                           columnIndex,
                         }: RankSpanMethodProps) => {
  if (row && rowIndex >= 0) {
    let num = 1
    // 根据columnIndex判断需要判断值是否相等的字段
    if (columnIndex === 1) {
      num = rankRowSpan(row, rowIndex, 'type', rankData.value)
    }
    return {
      rowspan: num,
      colspan: 1,
    };
  }
}

const rankCheckedSpanMethod = ( {
                           row,
                           column,
                           rowIndex,
                           columnIndex,
                         }: RankSpanMethodProps) => {
  if (row && rowIndex >= 0) {
    let num = 1
    // 根据columnIndex判断需要判断值是否相等的字段
    if (columnIndex === 1) {
      num = rankRowSpan(row, rowIndex, 'type', rankCheckedData.value)
    } else if (columnIndex === 4) {
      num = rankCheckedData.value.length;
    }
    return {
      rowspan: num,
      colspan: 1,
    };
  }
}

let nowRankRowSpan = 1;
const rankRowSpan = (row: IRankAdjust | IRankCensor, rowIndex: number, str: string, data: Array<IRankAdjust> | Array<IRankCensor>): number => {
  let num: number = 0;
  let isEqual: boolean = false;
  let isNextEqual: boolean = false;
  if (str === 'type') {
    isEqual = rowIndex > 0 && row.type == data[rowIndex - 1].type;
    isNextEqual = rowIndex + 1 < data.length && row.type == data[rowIndex + 1].type;
  }

  /**
   * 判断上一行字段的值与该行值是否一致
   */
  if (nowRankRowSpan === 1 && isEqual) {
    return 0
  }
  /**
   * 判断下一行字段的值与该行值是否一致
   */
  if (isNextEqual) {
    nowRankRowSpan += 1;
    num = rowIndex + 1;
    return rankRowSpan(data[num], num, str, data);
  } else {
    num = nowRankRowSpan;
    nowRankRowSpan = 1;
    return num;
  }
}
let minRankUpdateId: number | undefined = undefined;

const handleUpdateRank = () => {
  if (minRankUpdateId && partyForm.value.length > 0) {
    const rankMap = new Map();
    const arrayToSave = [] as Array<IParty>;
    const party = {} as IParty;
    party.bonus = [];
    party.negative = [];
    party.id = minRankUpdateId;
    rankData.value.forEach((item: IRankAdjust) => {
      const execute = {} as IExecute;
      if (item.isCheck && item.type === '提升等次') {
        execute.data = item.situation;
        execute.remark = item.remark;
        party.bonus.push(execute);
      } else if (item.isCheck && item.type === '降低等次') {
        execute.data = item.situation;
        execute.remark = item.remark;
        party.negative.push(execute);
      }
    })
    arrayToSave.push(party);
    // 计算得分
    const scoreParty = computeScore(partyForm.value);
    scoreParty.id = minRankUpdateId;
    scoreParty.partyName = party.partyName;
    scoreParty.partyTime = party.partyTime;
    arrayToSave.push(scoreParty);
    //标记待审核
    arrayToSave.push(...handleCensorData(rankCensorData.value, '待审核'));
    // end
    updatePartyBuilding({total: arrayToSave.length, updateBuilding: JSON.stringify(arrayToSave)}).catch(error => {
      console.error(error);
      DialogUtils.showErrorBox('温馨提示', '党建信息更新失败');
    })
  } else {
    DialogUtils.showErrorBox('温馨提示', '数据异常，请联系管理员！');
    return;
  }
}

const handleUpdateRankScore = () => {
  const forms = Utils.cloneObject(partyForm.value);
  const form = forms[0];
  form.bonus = [];
  form.negative = [];
  rankData.value.forEach((item: IRankAdjust) => {
    const execute = {} as IExecute;
    if (item.isCheck && item.type === '提升等次') {
      execute.data = item.situation;
      execute.remark = item.remark;
      form.bonus.push(execute);
    } else if (item.isCheck && item.type === '降低等次') {
      execute.data = item.situation;
      execute.remark = item.remark;
      form.negative.push(execute);
    }
  })
  computeScore(forms);
}

interface SpanMethodProps {
  row: IProperty
  column: TableColumnCtx<IProperty>
  rowIndex: number
  columnIndex: number
}

const objectSpanMethod = ({
                            row,
                            column,
                            rowIndex,
                            columnIndex,
                          }: SpanMethodProps) => {

  if (row && row.index >= 0) {
    const property = partyForm.value[row.index].property;
    let num = 1
    // 根据columnIndex判断需要判断值是否相等的字段
    if (columnIndex === 1) {
      num = recursionRowSpan(row, rowIndex, 'projectName', property)
    }
    if (columnIndex === 2) {
      num = recursionRowSpan(row, rowIndex, 'checkey', property)
    }
    if (columnIndex === 3) {
      num = recursionRowSpan(row, rowIndex, 'evaluationType', property)
    }
    return {
      rowspan: num,
      colspan: 1,
    };
  }
}
let nowRowSpan = 1;
const recursionRowSpan = (row: IProperty, rowIndex: number, str: string, data: Array<IProperty>): number => {
  let num: number = 0;
  let isEqual: boolean = false;
  let isNextEqual: boolean = false;
  if (str === 'projectName') {
    isEqual = rowIndex > 0 && row.projectName == data[rowIndex - 1].projectName;
    isNextEqual = rowIndex + 1 < data.length && row.projectName == data[rowIndex + 1].projectName;
  } else if (str === 'checkey') {
    isEqual = rowIndex > 0 && row.checkey == data[rowIndex - 1].checkey;
    isNextEqual = rowIndex + 1 < data.length && row.checkey == data[rowIndex + 1].checkey;
  } else if (str === 'evaluationType') {
    isEqual = rowIndex > 0 && row.evaluationType == data[rowIndex - 1].evaluationType;
    isNextEqual = rowIndex + 1 < data.length && row.evaluationType == data[rowIndex + 1].evaluationType;
  }

  /**
   * 判断上一行字段的值与该行值是否一致
   */
  if (nowRowSpan === 1 && isEqual) {
    return 0
  }
  /**
   * 判断下一行字段的值与该行值是否一致
   */
  if (isNextEqual) {
    nowRowSpan += 1;
    num = rowIndex + 1;
    return recursionRowSpan(data[num], num, str, data);
  } else {
    num = nowRowSpan;
    nowRowSpan = 1;
    return num;
  }
}

const getAppraiseLabel = (evaluationType: string) => {
  return evaluationType === '工作推进与制度执行' ? '完成' : evaluationType === '工作质量与实际成效' ? '达标' : '有';
}

const changePartyForm2Array = (form: IPartyForm): Array<IParty> => {
  const needToSave = new Map();
  const party = {} as IParty;
  party.partyName = form.partyName;
  party.partyTime = form.partyTime;
  party.partyType = form.partyType;
  party.execute1 = [];
  party.execute2 = [];
  party.execute3 = [];
  form.property.forEach((item: IProperty) => {
    party.id = item.id;
    party.projectName = item.projectName;
    let saveItem = needToSave.get(item.projectName);
    if (!saveItem) {
      saveItem = Utils.cloneObject(party);
      needToSave.set(item.projectName, saveItem);
    }
    const execute = {} as IExecute;
    execute.data = item.isCheck ? item.evaluation : undefined;
    execute.remark = item.remark;
    if ('工作推进与制度执行' === item.evaluationType && execute.data) {
      saveItem.execute1.push(execute);
    } else if ('工作质量与实际成效' === item.evaluationType && execute.data) {
      saveItem.execute2.push(execute);
    } else if ('有无严禁发生的行为' === item.evaluationType && execute.data) {
      saveItem.execute3.push(execute);
    }
  })
  const partyArray = [] as Array<IParty>;
  needToSave.forEach((value, key) => {
    partyArray.push(value);
  })
  return partyArray;
}
/**
 * 客观评定结果
 * @param row
 */
const handleCensor = (row: IRankCensor) => {
  if (partyInfo.value.length > 0) {
    const arrayToSave = handleCensorData(row, '已审核');
    // end
    updatePartyBuilding({total: arrayToSave.length, updateBuilding: JSON.stringify(arrayToSave)}).catch(error => {
      console.error(error);
      DialogUtils.showErrorBox('温馨提示', '党建信息更新失败');
    })
  } else {
    DialogUtils.showErrorBox('温馨提示', '数据异常，请联系管理员！');
    return;
  }
}
/**
 * 要求重新评估
 * @param row
 */
const handleResetAssess = (row: IRankCensor) => {
  if (partyInfo.value.length > 0) {
    const arrayToSave = handleCensorData(row, '审核未通过');
    // end
    updatePartyBuilding({total: arrayToSave.length, updateBuilding: JSON.stringify(arrayToSave)}).catch(error => {
      console.error(error);
      DialogUtils.showErrorBox('温馨提示', '党建信息更新失败');
    })
  } else {
    DialogUtils.showErrorBox('温馨提示', '数据异常，请联系管理员！');
    return;
  }
}

const handleCensorData = (row: IRankCensor, status: string) => {
  partyCensorStatus.value = status;
  const arrayToSave = [] as Array<IParty>;
  row.status = status;
  partyInfo.value.forEach(item => {
    // 计算得分
    const scoreParty = {} as IParty;
    scoreParty.id = item.id;
    scoreParty.partyName = item.partyName;
    scoreParty.partyTime = item.partyTime;
    scoreParty.censorRemark = row.remark;
    scoreParty.censorScore = adjustScoreLabel(row.scoreLabel);
    scoreParty.censorStatus = row.status;
    arrayToSave.push(scoreParty);
  })
  return arrayToSave;
}

/**
 * 提交更新
 */
const handleUpdate = (form: IPartyForm) => {
  const arrayToSave = changePartyForm2Array(form);
  // 计算得分
  const scoreParty = computeScore(partyForm.value);
  if (minRankUpdateId === undefined) {
    DialogUtils.showWarningBox('温馨提示', '数据处理异常，请联系管理员');
    return;
  }
  scoreParty.id = minRankUpdateId;
  scoreParty.partyName = form.partyName;
  scoreParty.partyTime = form.partyTime;
  arrayToSave.push(scoreParty);
  //标记待审核
  arrayToSave.push(...handleCensorData(rankCensorData.value, '待审核'));
  // end
  updatePartyBuilding({total: arrayToSave.length, updateBuilding: JSON.stringify(arrayToSave)}).catch(error => {
    console.error(error);
    DialogUtils.showErrorBox('温馨提示', '党建信息更新失败');
  })
}

/**
 * 提交更新
 */
const handleUpdateScore = (form: IPartyForm) => {
  const arrayToSave = changePartyForm2Array(form);
  // 计算得分
  const scoreParty = computeScore(partyForm.value);
}

const emit = defineEmits(['update:visible', 'update:operate', 'reload:data']);

watch(
    () => formVisible.value,
    (val) => {
      emit('update:visible', val);
    },
);

watch(
    () => props.visible,
    (val) => {
      formVisible.value = val;
    },
);

watch(
    () => formOperate.value,
    (val) => {
      emit('update:operate', val);
    },
);

watch(
    () => props.operate,
    (val) => {
      formOperate.value = val;
      console.warn(formOperate.value);
    },
);

watch(
    () => props.data,
    (val) => {
      if (val) {
        partyInfo.value = val;
        initPartyInfo(partyInfo.value);
      } else {
        partyInfo.value = [];
      }
    },
);

</script>

<style scoped lang="scss">
.partyInfo {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
}
.party {
  overflow: hidden;
}
.title {
  font-size: 22px;
  text-align: center;
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  margin: 0 70px;
  font-weight: bold;
}
.full {
  width: 100% !important;
  height: 100% !important;
}

.maximize {
  position: absolute;
  top: 23px;
  right: 40px;
  padding: 0;
  width: 54px;
  height: 54px;
  background: 0 0;
  border: none;
  outline: 0;
  cursor: pointer;
  font-size: var(--el-message-close-size,16px);
}

.tabs {
  height: 70vh;
  //overflow-y: auto;
  border-top: 1px solid #eff1f4;
  border-bottom: 1px solid #eff1f4;
}

.censor {
  display: flex;
  gap: 10px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>